package com.vcar.LDiceClient.core
{
    import com.vcar.LDiceClient.config.Config;

    import flash.display.DisplayObject;

    import mx.collections.ArrayCollection;
    import mx.containers.Canvas;
    import mx.core.Container;
    import mx.core.ScrollPolicy;
    import mx.events.ResizeEvent;

    /**
     * 系统popupmanager的替代类
     * @author rhj
     * 系统的popupmanager弹出窗口是放在所有界面的最顶层的，如有游戏里有蒙板层，蒙板无法挡信弹出窗口。
     * 这个类的弹出方式为，把弹出的窗口作为child加载到场景较顶层（在蒙板层下）的一个compenet中。
     */
    public class PopUpManager
    {

        //************************** 上面内容为单例实现

        private static const BACKGROUND_COLOR:uint = 0;							//如果为模态窗口时，背景层的背景色
        private static const BACKGROUND_ALPHA:Number = 0.5;						//背景Alpha度

        private static var _baseContainer:Container;								//用于装载Window的最底层容器
        private static var _modalMask:Canvas;										//模态窗口时的遮盖层
        private static var _windowList:ArrayCollection;							//window列表，存放着当前打开了的窗口对像，该列表存放的对象格式为：Object,其中obj.window为该窗口对象,obj.modal为该窗口是否为模态
        private static var _currentModalWindow:DisplayObject;						//当前的最前端顶层窗口
        private static var _topWindow:DisplayObject;

        /**
         * 弹出窗口管理器的初始化函数
         *
         * @param baseContainer 该参数为指定该管理器所管理的窗口的宿主容器，也就是说弹出窗口放在哪个窗口里，作为该窗口的子项
         *
         * */
        public static function initialize(baseContainer:Container):void
        {
            if(!baseContainer){
                throw new Error('baseContainer 参数不能为空');
            }

            _windowList = new ArrayCollection();
            _baseContainer = baseContainer;
            _baseContainer.horizontalScrollPolicy = ScrollPolicy.OFF;
            _baseContainer.verticalScrollPolicy = ScrollPolicy.OFF;
            _baseContainer.addEventListener(ResizeEvent.RESIZE,__baseContainerResizeHandler);
        }

        /**
         * 向窗口中添加一个窗口。
         *
         * @param window 需要添加的弹出窗口对象
         *
         * @param modal 指定该弹出窗口是否为模态，默认值为false
         *
         * */
        public static function addPopUp(window:DisplayObject,modal:Boolean=false):void
        {
            if(!window)
                return;

            var obj:Object = {window:window,modal:modal};
            var i:int = hasExist(window);
            if(i > -1){
                bringToFront(window);
            }else{
                _windowList.addItem(obj);
                checkTheModal(window,modal);
                _baseContainer.addChild(window);
            }
            _topWindow = window;
        }

        /**
         * 将窗口居中
         * @param window
         *
         */		
        public static function centerPopUp(window:DisplayObject):void
        {
            if(window==null)
            {
                return;
            }
//            window.x=Math.round((Config.stageWidth - window.width)/2);
//            window.y=Math.round((Config.stageHeight - window.height)/2);
        }


        public static function contains(window:DisplayObject):Boolean
        {
            if(window == null){
                return false;
            }else{
                return _baseContainer.contains(window);
            }
        }

        public static function removePopUp(window:DisplayObject):void
        {
            if(!window)
                return;

            if(!_baseContainer.contains(window))
                throw new Error('弹出窗口容器里没有该弹出窗口');

            var i:int = _windowList.length-1;
            for(;i>-1;i--){
                var obj1:Object = _windowList.getItemAt(i);
                if(obj1.window == window){
                    _windowList.removeItemAt(i);
                    break;
                }
            }

            if(i == -1)
                throw new Error('弹出窗口列表里没有该弹出窗口');

            if(window == _currentModalWindow){
                _baseContainer.removeChild(window);
                _baseContainer.removeChild(_modalMask);
                _currentModalWindow = null;
                for(var j:int=i-1;j>-1;j--){
                    var obj2:Object = _windowList.getItemAt(j);
                    if(obj2.modal == true){
                        var tmp:int = _baseContainer.getChildIndex(obj2.window as DisplayObject);
                        _baseContainer.addChildAt(_modalMask,tmp);
                        _currentModalWindow = obj2.window;
                        break;
                    }
                }
            }else{
                _baseContainer.removeChild(window);
            }

            if(window == _topWindow){
                if(_baseContainer.numChildren == 0)
                    _topWindow = null;
                else
                    _topWindow = _baseContainer.getChildAt(_baseContainer.numChildren-1);
            }
        }

        public static function removeAllPopUp():void
        {
            _windowList.removeAll();
            _baseContainer.removeAllChildren();
        }

        public static function bringToFront(window:DisplayObject):void
        {
            var i:int = hasExist(window);
            if(i > -1){
                var obj:Object = _windowList.removeItemAt(i);
                _windowList.addItem(obj);
                checkTheModal(obj.window,obj.modal);
                displayListBringToFront(obj.window);
            }
        }

        private static function displayListBringToFront(window:DisplayObject):void
        {
            if(_baseContainer.contains(window)){
                var index:int = _baseContainer.getChildIndex(window);
                var len:int = _baseContainer.numChildren;
                while(index < (len-1)){
                    _baseContainer.swapChildrenAt(index,index+1);
                    index++;
                }
            }
        }

        /**
         *
         * @param window
         * @param m
         *
         */
        private static function checkTheModal(window:DisplayObject,m:Boolean):void
        {
            if(m){

                /**
                 * 这段代码很垃圾，有待优化
                 * _modalMask是新手教程的mask,首先把这个做popupmanager里就是很不合理，让popupmanger的功能不干不净
                 * 其次_modalMask不能这样初始化，当用户第一次添加pop时初始化，而是应该放在popupmanger初始化时初始化。
                 *
                 * */
                if(!_modalMask){
                    createModalMask();
                    _baseContainer.addChild(_modalMask);
                }else{
                    if(_baseContainer.contains(_modalMask))
                        displayListBringToFront(_modalMask);
                    else
                        _baseContainer.addChild(_modalMask);
                }

                _currentModalWindow = window;
            }
        }

        private static function hasExist(window:DisplayObject):int
        {
            var len:int = _windowList.length;
            while(len>0){
                var obj:Object = _windowList.getItemAt(len-1);
                if(window == obj.window)
                    return (len-1);
                len--;
            }

            return -1;
        }

        private static function createModalMask():void
        {
            if(_modalMask)
                return;

            _modalMask = new Canvas();
            _modalMask.percentWidth = 100;
            _modalMask.percentHeight = 100;
            _modalMask.setStyle('backgroundColor',BACKGROUND_COLOR);
            _modalMask.setStyle('backgroundAlpha',BACKGROUND_ALPHA);
        }

        private static function __baseContainerResizeHandler(e:ResizeEvent):void
        {

        }

    }
}

